package com.redis.controller;

import com.redis.lock.RedisLock;
import com.redis.lock.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

/**
 * @author zzm
 * @version V1.0
 * @Description 测试接口
 * @date 2017-09-26 10:42
 **/
@Controller
public class TestController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    private RLock lock = RedisLock.create("springboot", 3);

    @GetMapping("/index/lock")
    @ResponseBody
    public Object index() {
        try {
            lock.lock(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
        return "success";
    }

    @GetMapping("/index/trylock")
    @ResponseBody
    public Object trylock() {
        boolean locked;
        try {
            locked = lock.tryLock(3, 10, TimeUnit.SECONDS);
            if (locked) {
                logger.info(Thread.currentThread().getId() + "已加锁");
            } else {
                logger.info(Thread.currentThread().getId() + "加锁超时");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return "success";
    }

    @GetMapping("/test")
    @ResponseBody
    public Object test() {
        return null;
    }
}

